package com.sky.service.impl.user;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.user.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    // 微信登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后
    // 传到开发者服务器调用此接口完成登录流程的接口url
    private static final String CODE2SESSION_Url = "https://api.weixin.qq.com/sns/jscode2session";

    // 授权类型
    private static final String GRANT_TYPE = "authorization_code";


    // 微信配置类对象
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public User login(UserLoginDTO dto) {
        log.info("小程序端传递过来的用户code为{}", dto);

        // 封装请求参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", dto.getCode());
        map.put("grant_type", GRANT_TYPE);

        // 获取到微信端返回数据
        //属性	        类型	说明
        //session_key	string	会话密钥
        //unionid	    string	用户在开放平台的唯一标识符，若当前小程序已绑定到微信开放平台账号下会返回，详见 UnionID 机制说明。
        //errmsg	    string	错误信息
        //openid	    string	用户唯一标识
        //errcode	    int32	错误码
        String jsonDate = HttpClientUtil.doGet(CODE2SESSION_Url, map);
        log.info("微信接口返回数据为：{}", jsonDate);
        // 微信接口返回数据为：{"session_key":"Ws0u/Snxp7ga1fxACgtpRQ==","openid":"oLsGs6xsPdiwXLD_koN2rEo9FUm4"}

        // 获取openid
        JSONObject jsonObject = JSONObject.parseObject(jsonDate);
        String openId = jsonObject.getString("openid");

        // 根据openid判断该用户是否为新用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getOpenid,openId);
        User user = userMapper.selectOne(wrapper);

        if (user == null) {
            user = User.builder().openid(openId).createTime(LocalDateTime.now()).build();
            userMapper.insertUser(user);
        }

        return user;
    }
}
